
TIME_STANDART = "0:0:0:0:0:0" # years:months:weeks:days:hours:minutes

def convert_text_to_time(time="", text=""):
    time_names = [ 'year', 'month', 'week',
                   'day', 'hour', 'minute' ]

    index = 0
    for name in time_names: 
        if text in [name, name+"s"]: return TIME_STANDART[:index] + time + TIME_STANDART[index+1:]
        index += 2

def convert_shared_to_time(shared=""):
    splited = shared.split()
    if len(splited) < 2: return TIME_STANDART

    time = convert_text_to_time(splited[0], splited[1])

    return time

def is_time_lowest_equal(ftime="", stime=""):
    if ftime == TIME_STANDART: return True

    fvalue, svalue = ftime.split(":"), stime.split(":")

    length = len(fvalue)-1
    while length > 0:
        fnum, snum = int(fvalue[length]), int(svalue[length])

        if fnum == 0 and snum > 0: return False
        if fnum > 0 and snum == 0: return True
        if fnum <= snum and fnum != 0: return True

        length -= 1

    return False


def sort_videos_to_shared_time(videos=[]):
    if videos == []: return videos

    vds, vds_values = [], []
    for video in videos:
        inserted = False
        value = convert_shared_to_time(video.shared)
        if len(vds) > 0:
            for i in range(0, len(vds)):
                if is_time_lowest_equal(value, vds_values[i]):
                    vds.insert(i, video)
                    vds_values.insert(i, value)
                    inserted = True
                    break
            if not inserted:
                vds.append(video)
                vds_values.append(value)
        else:
            vds.insert(0, video)
            vds_values.insert(0, value)

    return vds


